package com.sdkx.wear_os.viewmodel

import android.app.Activity
import android.app.Application
import android.content.Intent
import com.sdkx.wear_os.adapter.MineAdapter
import com.sdkx.wear_os.app.MyApplication
import com.sdkx.wear_os.app.MyApplication.Companion.fastKV
import com.sdkx.wear_os.base.BaseViewModel
import com.sdkx.wear_os.bean.Constant
import com.sdkx.wear_os.bean.MineBean
import com.sdkx.wear_os.retrofit.Bean
import com.sdkx.wear_os.retrofit.UserInfo
import com.sdkx.wear_os.retrofit.launch
import com.sdkx.wear_os.retrofit.launchData
import com.sdkx.wear_os.ui.activity.LoginActivity
import com.sdkx.wear_os.utils.ToastLogUtils
import com.sdkx.wear_os.utils.getVersionName
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.launch

/**
 * 我的
 */
class MineViewModel(application: Application) : BaseViewModel(application) {

    //我的适配器
    val mineAdapter = MineAdapter()

    init {
        val mineData = mutableListOf<MineBean>()
        mineData.add(MineBean("联系管理员", ""))
        mineData.add(MineBean("关于我们", ""))
        mineData.add(MineBean("版本更新", "当前版本:${getVersionName(MyApplication.application)}"))
        mineAdapter.submitList(mineData)
    }

    //个人信息
    private val _userInfoFlow = MutableSharedFlow<UserInfo>()
    val userInfoFlow: MutableSharedFlow<UserInfo>
        get() = _userInfoFlow

    //是否更新
    private val _updateFlow = MutableSharedFlow<Bean>()
    val updateFlow: MutableSharedFlow<Bean>
        get() = _updateFlow

    /**
     * 个人信息
     */
    fun getLoginUserInfo(context: Activity) {
        launch({ retrofitManager.getLoginUserInfo() }, {
            MainScope().launch {
                _userInfoFlow.emit(it)
            }
        }, {
        }, {
            context.startActivity(Intent(context, LoginActivity::class.java))
            context.finish()
        })
    }

    /**
     * 退出登录
     */
    fun logout(context: Activity) {
        launchData({ retrofitManager.logout() }, {
            fastKV.remove(Constant.APP_TOKEN)
            context.startActivity(Intent(context, LoginActivity::class.java))
            context.finish()
        }, {
            ToastLogUtils.toastUtil(it)
        }, {
            fastKV.remove(Constant.APP_TOKEN)
            context.startActivity(Intent(context, LoginActivity::class.java))
            context.finish()
        })
    }

    /**
     * 升级
     */
    fun getAndroidRvVersion() {
        launch({ retrofitManager.getAndroidRvVersion() }, {
            MainScope().launch {
                _updateFlow.emit(it)
            }
        }, {
            ToastLogUtils.toastUtil(it)
        }, {
        })
    }
}